package cn.com.startai.smartadh5.main.fragment;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.os.Process;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import cn.com.startai.smartadh5.R;
import cn.com.startai.smartadh5.db.db.entity.PlayInfo;
import cn.com.startai.smartadh5.db.db.manager.PlayInfoHelper;
import cn.com.startai.smartadh5.db.sp.SPManager;
import cn.com.startai.smartadh5.extension.utils.NmcUtils;
import cn.com.startai.smartadh5.extension.utils.musicplayer.CoverLoader;
import cn.com.startai.smartadh5.main.adapter.MusicListAdapter;
import cn.com.startai.smartadh5.main.service.musicplayer.OnPlayerEventListener;
import cn.com.startai.smartadh5.main.service.musicplayer.PlayService;
import cn.com.startai.smartadh5.main.view.AlbumCoverView;
import cn.com.startai.smartadh5.processlogic.entity.bean.player.PlayStateChangeBean;
import cn.com.startai.smartadh5.processlogic.entity.event.player.PlayModeChangedEvent;

/**
 * 音乐播放器
 */
public class MusicFragment extends BaseFragment {

    private static final int HANDLER_WHAT_LOAD_COVER = 0x01;
    private static final int HANDLER_WHAT_QUERY_PLAY_LIST = 0x02;

    @BindView(R.id.rl_root)
    RelativeLayout rlRoot;
    @BindView(R.id.acv_music)
    AlbumCoverView acvMusic;
    @BindView(R.id.iv_play)
    ImageView ivPlay;
    @BindView(R.id.tv_current)
    TextView tvCurrent;
    @BindView(R.id.progress)
    SeekBar sbProgress;
    @BindView(R.id.tv_total)
    TextView tvTotal;
    @BindView(R.id.ll_control)
    LinearLayout llControl;
    @BindView(R.id.tv_cur_music_name)
    TextView tvMusicName;
    @BindView(R.id.tv_singer)
    TextView tvSinger;
    @BindView(R.id.tv_album)
    TextView tvAlbum;
    @BindView(R.id.rv_music_list)
    RecyclerView rvMusicList;

    DateFormat dateFormat = new SimpleDateFormat("mm:ss", Locale.getDefault());

    private List<PlayInfo> mPlayList = new ArrayList<>();
    private MusicListAdapter adapter;
//    private MusicListAdapterV1 adapterV1;

    private PlayInfo curPlay;
    private long totalTime;
    //当前进度 百分比，用于回云端
    private int curPercent;

    private boolean isAutoPlay = true;

    private HandlerThread mHandlerThread;
    private Handler mHandler;

    private PlayService playService;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            playService = ((PlayService.PlayBinder) service).getService();

            playService.setOnPlayEventListener(new OnPlayerEventListener() {
                @Override
                public void onChange(PlayInfo music) {
                    curPlay = music;
                    totalTime = music.getDuration();
                    curPercent = 0;
                    String musicName = music.getFileName()
                            .substring(0, music.getFileName().lastIndexOf("."));

                    tvMusicName.setText(musicName);
                    tvTotal.setText(formatTime(totalTime));
                    sbProgress.setProgress(0);
                    sbProgress.setMax((int) (music.getDuration() / 1000));
                    if (!TextUtils.isEmpty(music.getAlbum())) {
                        tvAlbum.setText(String.format(getString(R.string.audio_album), music.getAlbum()));
                    } else {
                        tvAlbum.setText(String.format(getString(R.string.audio_album), ""));
                    }
                    if (!TextUtils.isEmpty(music.getAuthor())) {
                        tvSinger.setText(String.format(getString(R.string.audio_singer), music.getAuthor()));
                    } else {
                        tvSinger.setText(String.format(getString(R.string.audio_singer), ""));
                    }
                    for (int i = 0; i < mPlayList.size(); i++) {
                        PlayInfo info = mPlayList.get(i);
                        info.setPlaying(false);
                        if (music.getId().equals(info.getId())) {
                            info.setPlaying(true);
                        }
                    }
                    adapter.notifyDataSetChanged();
//                    adapterV1.notifyDataSetChanged();
                    rvMusicList.scrollToPosition(playService.getPlayingPosition());
                    Log.i("MusicFragment","Position ="+playService.getPlayingPosition());

                    setCover(music);
                }

                @Override
                public void onPlayerStart() {
                    //开启动画
                    acvMusic.start();
                    Log.i("MusicFragment","动画播放");
                    ivPlay.setSelected(true);
                    NmcUtils.sendToNmcPlayerStatusChanged(curPlay.getFileId(), PlayStateChangeBean.STATUS_PLAY, curPercent);
                }

                @Override
                public void onPlayerPause() {
                    acvMusic.pause();
                    ivPlay.setSelected(false);
                    //回复云端
                    NmcUtils.sendToNmcPlayerStatusChanged(curPlay.getFileId(), PlayStateChangeBean.STATUS_PAUSE, curPercent);

                }

                @Override
                public void onPublish(int progress) {
                    tvCurrent.setText(formatTime(progress));
                    sbProgress.setProgress(progress / 1000);
                    int percent = (int) (progress * 1.0f / totalTime * 100);
                    if (percent != curPercent) {
                        curPercent = percent;
                        //回复云端
                        NmcUtils.sendToNmcPlayerStatusChanged(curPlay.getFileId(), PlayStateChangeBean.STATUS_PLAY, curPercent);
                    }
                }

                @Override
                public void onBufferingUpdate(int percent) {

                }

                @Override
                public void onTimer(long remain) {

                }

                @Override
                public void onMusicListUpdate() {

                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    private int isMusic;

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_music, container, false);
    }

    @Override
    public void initData() {
        testOk();
        Intent serviceIntent = new Intent(mContext, PlayService.class);
        mContext.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);

        initHandler();
        setCover(null);

        EventBus.getDefault().register(this);
    }

    private void initHandler() {
        mHandlerThread = new HandlerThread("[MusicFragment.HandlerThread]", Process.THREAD_PRIORITY_BACKGROUND);
        mHandlerThread.start();
        mHandler = new Handler(mHandlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case HANDLER_WHAT_LOAD_COVER:
                        PlayInfo music = (PlayInfo) msg.obj;
                        Bitmap albumBitmap = CoverLoader.getInstance().loadRound(music);
                        Bitmap albumBlurBitmap = CoverLoader.getInstance().loadBlur(music);
                        mContext.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                acvMusic.setCoverBitmap(albumBitmap, false);
                                rlRoot.setBackground(new BitmapDrawable(getResources(), albumBlurBitmap));
                            }
                        });
                        break;
                    case HANDLER_WHAT_QUERY_PLAY_LIST:
                        if (playService == null) {
                            return;
                        }
                        //查询播放列表
                        List<PlayInfo> playList = PlayInfoHelper.getInstance()
                                .queryListByType(PlayInfo.TYPE_MUSIC);

                        NmcUtils.sendToNmcPlayListChanged(PlayInfo.TYPE_MUSIC, playList);

                        if (playList.isEmpty()) {
                            NmcUtils.sendToNmcPlayerStatusChanged(-1, 0, 0);
                            return;
                        }
                        long playId = SPManager.getInstance().getCurrentAudioPlayId();
                        int playProgress = SPManager.getInstance().getCurrentAudioPlayProgress();

                        mContext.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                int position = 0;
                                PlayInfo needPlay = null;
                                if (playId != -1) {
                                    for (int i = 0; i < playList.size(); i++) {
                                        if (playList.get(i).getId().equals(playId)) {
                                            needPlay = playList.get(i);
                                            position = i;
                                            break;
                                        }
                                    }
                                }
                                setUp(playList);
                                playService.play(position);
                                Log.i("MusicFragment","handler播放");
                                if (needPlay != null) {
                                    playService.seekTo((int) ((playProgress * 1.0f / 100) * needPlay.getDuration()));
                                }
                            }
                        });
                        break;
                    default:
                        break;
                }
            }
        };
    }

    /**
     * 设置封面图
     */
    private void setCover(PlayInfo music) {
        Message msg = mHandler.obtainMessage();
        msg.what = HANDLER_WHAT_LOAD_COVER;
        msg.obj = music;
        msg.sendToTarget();
    }

    /**
     * 设置播放内容
     *
     * @param playList 播放列表
     */
    public void setUp(List<PlayInfo> playList) {
        if (playService == null) {
            return;
        }
        mPlayList.clear();
        mPlayList.addAll(playList);
        adapter.notifyDataSetChanged();
//        adapterV1.notifyDataSetChanged();
        playService.setPlayList(mPlayList);
    }

    /**
     * 追加播放列表
     */
    public void appendAudioList(List<PlayInfo> playList) {
        if (playService == null) {
            return;
        }
        mPlayList.addAll(playList);
        adapter.notifyDataSetChanged();
//        adapterV1.notifyDataSetChanged();
        playService.addPlayList(playList);
    }

    /**
     * 播放
     *
     * @param position 播放的位置
     */
    public void play(int position) {
        if (playService == null) {
            return;
        }
        playService.play(position);
    }

    @Override
    public void initView() {
        acvMusic.initNeedle(false);

        adapter = new MusicListAdapter(mContext, mPlayList);
//        adapterV1= new MusicListAdapterV1(mContext,mPlayList);
        rvMusicList.setLayoutManager(new LinearLayoutManager(mContext));
        rvMusicList.setAdapter(adapter);
    }

    @Override
    public void addViewListener() {

    }

    @Override
    public void onLeftPress() {
        super.onLeftPress();
        if (playService == null) {
            return;
        }
        playService.prev();
    }

    @Override
    public void onRightPress() {
        super.onRightPress();
        if (playService == null) {
            return;
        }
        playService.next();
    }

    private String formatTime(long time) {
        return dateFormat.format(new Date(time));
    }


    /**
     * 改变播放状态
     *
     * @param state 要改变的状态
     */
    public void changePlayState(PlayStateChangeBean state) {
        if (playService == null) {
            return;
        }
        PlayInfo currentPlayInfo = playService.getPlayingMusic();
        int fileId = state.getFileId();
        if (currentPlayInfo != null) {
            if (fileId == currentPlayInfo.getFileId()) {
                if (state.getStatus() == PlayStateChangeBean.STATUS_PLAY) {
                    if (playService.isPausing()) {
                        playService.start();
                        Log.i("MusicFragment","changePlayState");
                    }
                    isAutoPlay = true;
                    playService.seekTo((int) ((state.getProgress() * 1.0f / 100) * currentPlayInfo.getDuration()));
                } else {
                    if (playService.isPlaying()) {
                        playService.pause();
                    }
                    isAutoPlay = false;
                }
            } else {
                for (int i = 0; i < mPlayList.size(); i++) {
                    PlayInfo playInfo = mPlayList.get(i);
                    if (playInfo.getFileId() == state.getFileId()) {
                        isAutoPlay = true;
                        playService.play(i);
                        Log.i("MusicFragment","changePlayState");
                        playService.seekTo((int) ((state.getProgress() * 1.0f / 100) * currentPlayInfo.getDuration()));
                        break;
                    }
                }
            }
        }

    }

    /**
     * 删除指定播放记录
     *
     * @param removeFileId 当前删除的播放记录，>-1 为删除单条，=-1为清空操作
     */
    public void removePlayInfo(int removeFileId) {
        if (playService == null) {
            return;
        }
        if (removeFileId > -1) {
            //删除单条
            int position = -1;
            for (int i = 0; i < mPlayList.size(); i++) {
                PlayInfo info = mPlayList.get(i);
                if (info.getFileId().equals(removeFileId)) {
                    position = i;
                    break;
                }
            }
            if (position > -1) {
                mPlayList.remove(position);
                adapter.notifyDataSetChanged();
//                adapterV1.notifyDataSetChanged();

                playService.removePlayInfo(position);

                if (mPlayList.isEmpty()) {
                    resetUi();
                }
            }
        } else {
            playService.clearPlayList();
            mPlayList.clear();
            resetUi();
        }
    }

    public void setLoopMode(int mode) {
        if (playService == null) {
            return;
        }
        playService.setLoopMode(mode);
    }

    private void resetUi() {
        tvMusicName.setText("");
        tvSinger.setText("");
        tvAlbum.setText("");
        tvTotal.setText("00:00");
        tvCurrent.setText("00:00");
        sbProgress.setProgress(0);
//        adapterV1.notifyDataSetChanged();
        adapter.notifyDataSetChanged();
        ivPlay.setSelected(false);
        acvMusic.reset();
        setCover(null);
    }

    @SuppressWarnings("unused")
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onPlayModeChange(PlayModeChangedEvent event) {
        if (event.getMode() == PlayInfo.TYPE_MUSIC) {
            if (!isInit) {
                mHandler.sendEmptyMessage(HANDLER_WHAT_QUERY_PLAY_LIST);
                isInit = true;
                return;
            }
            NmcUtils.sendToNmcPlayListChanged(PlayInfo.TYPE_MUSIC, mPlayList);
            if (playService == null) {
                return;
            }
            if (isAutoPlay) {
                if (mPlayList.isEmpty()) {
                    NmcUtils.sendToNmcPlayerStatusChanged(-1, 0, 0);
                }
            } else {
                PlayInfo curPlay = playService.getPlayingMusic();
                if (curPlay != null) {
                    int percent = (int) (playService.getCurrentPosition() * 1.0f / totalTime * 100);
                    NmcUtils.sendToNmcPlayerStatusChanged(curPlay.getFileId(), PlayStateChangeBean.STATUS_PAUSE, percent);
                }
            }
        }
    }


    @Override
    public void onInVisible() {
        super.onInVisible();
        if (playService == null) {
            return;
        }
        Log.i("MusicFragment","onInVisible");
        playService.pause();
        SPUtils.getInstance().put("getindex",-1);
    }

    public boolean isInit = false;

    @Override
    public void onVisible() {
        super.onVisible();
        isAutoPlay=true;
        SPManager.getInstance().saveCurrentPlayerMode(PlayInfo.TYPE_MUSIC);
        if (playService == null) {
            return;
        }
        Log.i("MusicFragment","isInit="+isInit);
        Log.i("MusicFragment","isAutoPlay="+isAutoPlay);
         isMusic = SPUtils.getInstance().getInt("getindex");
        Log.i("MusicFragment","getindex="+isMusic);
        if(isMusic==2){
            if (isInit && isAutoPlay) {
                if (!mPlayList.isEmpty()) {
                    playService.start();
                    Log.i("MusicFragment", "onVisible");
                }
            }
        }
    }

//    @Override
//    public void onPause() {
//        super.onPause();
//        if (null!=playService){
//        playService.stop();
//        }
//        isAutoPlay=false;
//    }

//    @Override
//    public void onResume() {
//        super.onResume();
//        int code=SPUtils.getInstance().getInt("getMusic");
//        Log.i("MusicFragment","code="+code);
//        if(null!=playService&&code==3){
//        playService.play(curPercent);
//            Log.i("MusicFragment","onResume");
//        }
//        isAutoPlay=true;
//    }
     public int testOk(){
        return 666;
     }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        mHandler.removeCallbacksAndMessages(null);
        mHandler = null;
        playService.stop();
        mHandlerThread.quit();
        mHandlerThread = null;
    }
}
